package com.cgsd.heyu.ui.task;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.library.adapter.OnViewHelper;
import com.android.library.adapter.ViewHelper;
import com.apkfuns.logutils.LogUtils;
import com.cgsd.heyu.App;
import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.common.AvatarManger;
import com.cgsd.heyu.common.Constants;
import com.cgsd.heyu.entity.EventMessage;
import com.cgsd.heyu.entity.VideoEntity;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.presenter.BasePresenter;
import com.cgsd.heyu.presenter.home.HomePresenter;
import com.cgsd.heyu.ui.BaseActivity;
import com.cgsd.heyu.ui.task.vo.TaskDetailVo;
import com.cgsd.heyu.ui.video.JcvTaskDetailVideo;
import com.cgsd.heyu.ui.video.JcvTrillVideo;
import com.cgsd.heyu.utils.CommonTools;
import com.cgsd.heyu.utils.ImagePreviewActivity;
import com.cgsd.heyu.utils.RequestParams;
import com.cgsd.heyu.utils.StatusBarUtil;
import com.danikula.videocache.HttpProxyCacheServer;
import com.google.android.material.imageview.ShapeableImageView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import okhttp3.RequestBody;

/**
 * Author: sky on 2021/3/2 9:44
 * Email: xcode126@126.com
 * Desc: 任务详情
 */
public class TaskDetailActivity extends BaseActivity<BasePresenter> implements View.OnClickListener {

    private ShapeableImageView imageView;
    private TextView tvName;//发布人姓名
    private TextView tvId;//发布人用户ID
    private TextView tvStatus;//认证状态

    private TextView tvTitle;//任务标题
    private TextView tvLabel1;//标签一
    private TextView tvLabel2;//标签二
    private TextView tvAmount;//赏金金额
    private TextView tvCommitPeriod;//提交周期
    private TextView tvCheckPeriod;//审核周期
    private TextView tvRepeatOrder;//重复接单
    private TextView tvSystemLimit;//系统限制
    private TextView tvEndTime;//截止时间

    private TextView tvCompleteNum;//完成数量
    private TextView tvLastNum;//剩余数量
    private TextView tvTaskNum;//任务总量
    private TextView tvYetReward;//已发放赏金
    private TextView tvLastReward;//剩余赏金
    private TextView tvRewardTotal;//赏金总额

    private TextView tvKnow;//接单须知
    private TextView tvExplain;//接单说明
    private TextView tvStep;//任务步骤
    private TextView tvTeach;//任务教学
    private LinearLayout layoutStep;
    private TextView tvBooking;

    private int tid;
    private JcvTrillVideo mMpVideo;
    private LinearLayout mLLVideo;

    public static Intent getIntent(Context context, int tid) {
        return new Intent(context, TaskDetailActivity.class).putExtra("tid", tid);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_task_detail;
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.fullBar(this);
    }

    @Override
    protected void initView() {
        tid = getIntent().getIntExtra("tid", 0);
        bindViews();
    }

    @Override
    protected void initData() {
        getTaskDetail();
    }

    /**
     * init view id
     */
    private void bindViews() {
        imageView = findViewById(R.id.iv_avatar);
        tvName = findViewById(R.id.tv_name);
        tvId = findViewById(R.id.tv_id);
        tvStatus = findViewById(R.id.tv_status);

        tvTitle = findViewById(R.id.tv_task_title);
        tvLabel1 = findViewById(R.id.tv_label1);
        tvLabel2 = findViewById(R.id.tv_label2);
        tvAmount = findViewById(R.id.tv_amount);
        tvCommitPeriod = findViewById(R.id.tv_commit_period);
        tvCheckPeriod = findViewById(R.id.tv_check_period);
        tvRepeatOrder = findViewById(R.id.tv_repeat_order);
        tvSystemLimit = findViewById(R.id.tv_system_limit);
        tvEndTime = findViewById(R.id.tv_end_time);

        tvCompleteNum = findViewById(R.id.tv_complete_num);
        tvLastNum = findViewById(R.id.tv_last_num);
        tvTaskNum = findViewById(R.id.tv_task_num);
        tvYetReward = findViewById(R.id.tv_yet_reward);
        tvLastReward = findViewById(R.id.tv_last_reward);
        tvRewardTotal = findViewById(R.id.tv_reward_total);

        tvKnow = findViewById(R.id.tv_know);
        tvExplain = findViewById(R.id.tv_explain);
        tvStep = findViewById(R.id.tv_step);
        tvTeach = findViewById(R.id.tv_teach);
        layoutStep = findViewById(R.id.layout_step);

        tvBooking = findViewById(R.id.tv_booking);
        tvBooking.setOnClickListener(this);

        mMpVideo = findViewById(R.id.mp_video);
        mLLVideo = findViewById(R.id.ll_video);


    }

    /**
     * getTaskDetail
     */
    private void getTaskDetail() {
        RequestBody requestBody = new RequestParams()
                .putUid()
                .put("tid", tid)
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .getTaskDetail(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<TaskDetailVo>>() {
                    @Override
                    public void onSuccess(BaseResponse<TaskDetailVo> baseResponse) {
                        LogUtils.e("任务详情 ： " + baseResponse.toString());
                        processDetail(baseResponse.getBizBody());
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        // LogUtils.e("任务详情 ： "+error.getBody().toString());
                        setErrorMessage(error);
                    }
                });
    }

    /**
     * process detail
     *
     * @param detailVo
     */
    private void processDetail(TaskDetailVo detailVo) {

        LogUtils.e(TAG + ":" + detailVo.toString());
        AvatarManger.setAvatar(this, detailVo.gender, imageView);
        tvName.setText(detailVo.nick_name);
        tvId.setText(detailVo.user_id + "");
        tvStatus.setText(CommonTools.getStatus(detailVo.state));

        tvTitle.setText(detailVo.title);
        tvLabel1.setText("标签一");
        tvLabel2.setText("标签二");
        tvAmount.setText(String.format("%1$s%2$.2f", "￥", detailVo.price));
        tvCommitPeriod.setText(String.format("%1$s%2$s%3$s", getString(R.string.a_commit_period_), detailVo.finish, "小时"));
        tvCheckPeriod.setText(String.format("%1$s%2$s%3$s", getString(R.string.a_check_period_), detailVo.check, "小时"));
        tvRepeatOrder.setText(String.format("%1$s%2$s", getString(R.string.a_repeat_order_), detailVo.reply == 0 ? "否" : "是"));
        tvSystemLimit.setText(String.format("%1$s%2$s", getString(R.string.a_system_limit_), CommonTools.getLimitStr(detailVo.limit)));
        tvEndTime.setText(String.format("%1$s%2$s", getString(R.string.a_end_time_), detailVo.endtime));

        tvCompleteNum.setText(String.format("%1$s%2$s", getString(R.string.a_complete_num_), detailVo.tnum));//完成数量
        tvLastNum.setText(String.format("%1$s%2$s", getString(R.string.a_last_num_), (detailVo.num - detailVo.tnum)));//剩余数量
        tvTaskNum.setText(String.format("%1$s%2$s", getString(R.string.a_task_num_), detailVo.num));//任务总量

        int v = (int) (detailVo.price * detailVo.num);
        tvRewardTotal.setText(String.format("%1$s%2$s", getString(R.string.a_reward_total_), v));//赏金总额
        tvYetReward.setText(String.format("%1$s%2$s", getString(R.string.a_yet_reward_), detailVo.fnum));//已发放赏金
        tvLastReward.setText(String.format("%1$s%2$s", getString(R.string.a_last_reward_), (v - detailVo.fnum)));//剩余赏金

        tvKnow.setText(TextUtils.isEmpty(detailVo.content) ? "暂无内容" : detailVo.content);
        tvExplain.setText(TextUtils.isEmpty(detailVo.content1) ? "暂无内容" : detailVo.content1);
        tvTeach.setText(TextUtils.isEmpty(detailVo.content2) ? "暂无内容" : detailVo.content2);
        layoutStep.removeAllViews();
        if (detailVo.step != null && detailVo.step.size() > 0) {
//            StringBuilder sb = new StringBuilder();
            for (TaskDetailVo.StepBean step : detailVo.step) {
//                sb.append(step.step).append(".")
//                        .append(step.title)
//                        .append("\n");
                layoutStep.addView(getStepView(step));
            }
//            tvStep.setText(sb.toString());
        }
        tvBooking.setText(TextUtils.equals(detailVo.state, "1") ? "查看我的任务" : getString(R.string.a_now_booking));

        String videoUrl = detailVo.video;
        if (TextUtils.isEmpty(videoUrl)) {
            mLLVideo.setVisibility(View.GONE);
        } else {
            mLLVideo.setVisibility(View.VISIBLE);
            VideoEntity entity = new VideoEntity();
            entity.setVideoPlayUrl(videoUrl);
            entity.setVideoTitle("任务示例");

            mMpVideo.updateDatas(entity);
            mMpVideo.initStart();
            mMpVideo.setProgressListener(new JcvTrillVideo.PlayProgressListener() {
                @Override
                public void onPrepared() {
                    LogUtils.e("onPrepared");
                }
            });


        }
    }

    /**
     * join task
     */
    private void joinTask() {
        RequestBody requestBody = new RequestParams()
                .putUid()
                .put("tid", tid)
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .joinTask(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<Void>>() {
                    @Override
                    public void onSuccess(BaseResponse<Void> baseResponse) {
                        processJoinTask(baseResponse.getCode());
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        if (error.getCode() == 0 && error.getBody() != null) {
                            try {
                                dismissCommonSubmitDialog();
                                double v = (double) error.getBody();
                                startActivity(TaskCommitActivity.getIntent(TaskDetailActivity.this, (int) v));
                                finish();
                            } catch (NumberFormatException e) {
                                setErrorMessage(error);
                                finish();
                            }
                        } else {
                            setErrorMessage(error);
                        }
                    }
                });
    }

    /**
     * process join task
     *
     * @param code
     */
    private void processJoinTask(int code) {
        if (code == 200) {
            startActivity(TaskCommitActivity.getIntent(this, tid));
            EventBus.getDefault().post(new EventMessage<>(Constants.EventCode.TASK_REFRESH));
            finish();
        } else {
            showToast("接单出现异常，请稍后重试");
        }
    }

    @Override
    public void onClick(View view) {
        joinTask();
    }

    /**
     * get setp view
     *
     * @param item
     * @return
     */
    private View getStepView(TaskDetailVo.StepBean item) {
        return getHelperView(layoutStep, R.layout.item_publish_detail, new OnViewHelper() {
            @Override
            public void help(ViewHelper helper) {
                helper.setText(R.id.tv_step, "" + item.step);
                helper.setText(R.id.tv_step_title, "步骤" + item.step);
                helper.setText(R.id.tv_title, TextUtils.isEmpty(item.title) ? "暂无描述标题" : item.title);
                AvatarManger.setAvatar(TaskDetailActivity.this, item.image, helper.getView(R.id.iv_picture));
                helper.setText(R.id.tv_content, item.backcom);
                helper.setVisible(R.id.iv_picture, TextUtils.equals(item.backimg, "1"));
                helper.setVisible(R.id.tv_content, TextUtils.equals(item.backcom, "1"));
                helper.setOnClickListener(R.id.iv_picture, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<String> list = new ArrayList<>();
                        list.add(item.image);
                        startActivity(ImagePreviewActivity.getIntent(TaskDetailActivity.this, list, 0));
                    }
                });
            }
        });
    }
}
